package com.lishem.carl._01array;


/**
 * https://leetcode.cn/problems/spiral-matrix-ii/description/
 * <p>
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 * <p>
 * 示例 1：
 * <p>
 * 输入：n = 3
 * <p>
 * 输出：[[1,2,3],[8,9,4],[7,6,5]]
 * <p>
 * 示例 2：
 * <p>
 * 输入：n = 1
 * <p>
 * 输出：[[1]]
 */
public class _9LetCode59_螺旋矩阵II {

    public int[][] generateMatrix(int n) {
        int[][] arr = new int[n][n];
        int end = n - 1;
        int start = 0;
        int index = 1;
        int i = 0;
        while (start <= end) {
            if (start == end) {
                arr[start][start] = index;
            }
            i = start;
            while (i < end) {
                arr[start][i++] = index++;
            }
            i = start;
            while (i < end) {
                arr[i++][end] = index++;
            }
            i = end;
            while (i > start) {
                arr[end][i--] = index++;
            }
            i = end;
            while (i > start) {
                arr[i--][start] = index++;
            }
            start++;
            end--;
        }
        return arr;
    }

    public static void main(String[] args) {
        _9LetCode59_螺旋矩阵II sol = new _9LetCode59_螺旋矩阵II();
        printArr(sol.generateMatrix(1));
        System.out.println();
        printArr(sol.generateMatrix(2));
        System.out.println();
        printArr(sol.generateMatrix(3));
        System.out.println();
        printArr(sol.generateMatrix(4));
    }

    public static void printArr(int[][] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}
